<template>
  <div class="transaction">
    <header>
      <div class="btn-rules" @click="$router.push({path: '/rules'})">?</div>
      <p class="header-title">账户权益</p>
      <p class="benifit"><strong>{{userPosition.user.floatInter}}</strong></p>
      <table>
        <thead>
          <tr>
            <th>账户盈亏</th>
            <th>持仓手数</th>
            <th>持仓方向</th>
            <th>可用资金</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>{{userPosition.user.allBenifit}}</td>
            <td v-if="userPosition.position">{{userPosition.position.number}}</td>
            <td v-else>0</td>
            <td v-if="userPosition.position">{{userPosition.position.direction?'多头':'空头'}}</td>
            <td v-else>-</td>
            <td>{{userPosition.user.money}}</td>
          </tr>
        </tbody>
      </table>
    </header>
    <div class="charts">
      <div class="charts-wrapper" style="width:6.117rem;height:4.32rem;">
        <canvas id="charts"></canvas>
      </div>
      <div class="charts-main-info" style="">
        <p class="info-label">最新价</p>
        <p class="text-primary">{{latestPrice.price?latestPrice.price:0}}</p>
        <p class="info-label">保证金率</p>
        <p class="text-primary">{{`${latestPrice.surePrice?latestPrice.surePrice:0}%`}}</p>
        <p class="info-label">交易单位</p>
        <p class="text-primary">10吨/手</p>
      </div>
    </div>
    <div style="width: 100%;height:10px;background-color: #f5f5f5;margin: 0 -0.373rem"></div>
    <section style="padding: 0 10px 10px;">
      <h4 style="padding-bottom: 10px;"><span></span>市场消息<div><i class="el-icon-star-on"></i><i class="el-icon-star-on"></i><i class="el-icon-star-on"></i><i class="el-icon-star-on"></i><i class="el-icon-star-on"></i></div></h4>
      <div style="width: 100%;height:1px;background-color: #f5f5f5;margin: 0 -0.373rem"></div>
      <p class="news" style="">{{msg[0].msg}}</p>
      <p style="margin-top: 10px;">
        <el-input type="number" v-model="tradeNumber" placeholder="输入手数" style="width: 3.087rem;"></el-input>
        <el-button type="danger" class="btn" @click="trade(true)">买</el-button>
        <el-button type="success" class="btn" @click="trade(false)">卖</el-button>
        <el-button type="info" class="btn" @click="tradeClean">平</el-button>
      </p>
    </section>
  </div>
</template>

<script>
import { requestURL } from '@/config'
import F2 from '@antv/f2'
import axios from 'axios'

export default {
  name: 'Transaction',
  data () {
    return {
      msg: [{mgs: ''}],
      tradeNumber: 0,
      chart: null,
      latestPrice: {
        price: 0,
        surePrice: 0
      },
      userPosition: {
        user: {
          floatIner: 0,
          benifit: 0
        }
      }
    }
  },
  mounted () {
    const _this = this
    this.getLastestPrice()
    this.getUserPosition()
    this.getNews()
    this.$nextTick(() => {
      this.initCharts()
      // 112.124.10.169
      // 192.168.100.32
      const socket = new WebSocket('ws://act.hongtaqh.com:8899/websocket')

      // Connection opened
      socket.addEventListener('open', function (event) {
        socket.send('Hello Server!')
      })

      // Listen for messages
      socket.addEventListener('message', function (event) {
        _this.getLastestPrice()
        _this.getUserPosition()
        _this.getPriceList()
        _this.getNews()
        // console.log('Message from server ', event.data)
      })
      // Listen for messages
      socket.addEventListener('error', function (event) {
        // _this.$message('socket err')
        setInterval(function () {
          _this.getLastestPrice()
          _this.getUserPosition()
          _this.getPriceList()
          _this.getNews()
        }, 1000 * 60)
      })
      socket.addEventListener('close', function (event) {
        // _this.$message('socket close')
        setInterval(function () {
          _this.getLastestPrice()
          _this.getUserPosition()
          _this.getPriceList()
          _this.getNews()
        }, 1000 * 10)
      })
    })
  },
  methods: {
    initCharts () {
      function getList () {
        return axios.get(`${requestURL}/price/list`)
      }
      function getPosition () {
        return axios.get(`${requestURL}/user/positions?userName=${userName}&flag=false`)
      }
      const _this = this
      const userName = _this.$route.params.userName
      let data = []
      axios.all([getList(), getPosition()]).then(axios.spread(function (list, position) {
        list.data.map(element => {
          element.line = 'priceList'
        })
        position.data.map(element => {
          element.line = 'positionList'
        })
        // data = list.data.concat(position.data)
        data = list.data

        // Step 1: 创建 Chart 对象
        _this.chart = new F2.Chart({
          id: 'charts',
          width: document.querySelector('.charts-wrapper').offsetWidth,
          height: document.querySelector('.charts-wrapper').offsetHeight,
          pixelRatio: window.devicePixelRatio // 指定分辨率
        })
        _this.chart.axis('submitDate', {
          label: function label (text) {
            return {
              fontSize: 12,
              fill: '#ffffff'
            }
          }
        })
        _this.chart.axis('price', {
          label: function label (text) {
            return {
              fontSize: 12,
              fill: '#ffffff'
            }
          }
        })
        // Step 2: 载入数据源
        _this.chart.source(data, {
          submitDate: {
            type: 'timeCat',
            tickCount: 3,
            mask: 'hh:mm',
            range: [0, 1]
          }
        })
        _this.chart.legend(false)

        _this.chart.line().position('submitDate*price').color('white')

        // Step 4: 渲染图表
        _this.chart.render()
      })).catch(() => {
        // _this.$message.error('出错了')
      })
    },
    getPriceList () {
      const _this = this
      axios.get(`${requestURL}/price/list`).then(response => {
        _this.chart.changeData(response.data)
      })
    },
    getNews () {
      const _this = this
      axios.get(`${requestURL}/news/list`).then(response => {
        if (response.data.length > 0) {
          _this.msg = response.data
        }
      })
    },
    getLastestPrice () {
      const _this = this
      axios.get(`${requestURL}/price/`).then(response => {
        console.log('获取最新价格成功')
        _this.latestPrice = response.data
      }).catch(err => {
        console.log('获取最新价格失败')
        console.error(err)
      })
    },
    getUserPosition () {
      const _this = this
      const userName = _this.$route.params.userName
      axios.get(`${requestURL}/user/getPosition?userName=${userName}`).then(response => {
        _this.userPosition = response.data
      }).catch(() => {
        console.log()
      })
    },
    trade (bool) {
      const _this = this
      const userName = _this.$route.params.userName
      if (parseInt(_this.tradeNumber).macth(/^[1-9]\d*$/)) {
        axios.get(`${requestURL}/trade/?number=${_this.tradeNumber}&direction=${bool}&userName=${userName}`).then(response => {
          if (response.data === '交易成功') {
            _this.$message.success('下单成功')
            _this.getUserPosition()
          } else {
            _this.$message.error(response.data)
          }
        }).catch(() => {
          _this.$message.error('交易出错了，请重试')
        })
      }
    },
    tradeClean () {
      const _this = this
      const userName = _this.$route.params.userName
      if (!_this.userPosition.position || _this.userPosition.position.number === 0) {
        _this.$message.error('尚未持仓，请先进行交易')
      } else {
        axios.post(`${requestURL}/trade/clean?userName=${userName}`).then(response => {
          _this.$message.success('平仓成功')
          _this.getUserPosition()
        }).catch(() => {
          _this.$message.error('平仓失败')
        })
      }
    }
  }
}
</script>

<style>
.transaction {
  padding: 0.373rem;
  background-color: #ffffff;
  overflow-y: scroll;
}
.transaction header {
  position: relative;
  height: 4rem;
  background: url('../../static/imgs/tBg.png') no-repeat;
  background-size: cover;
  color: #ffffff;
  padding: 0.44rem;
  border-radius: 0.24rem;
}
.transaction header table {
  font-size: 0.393rem;
  width: 100%;
}
.transaction header table td {
  font-size: 0.473rem;
  text-align: center;
}
.header-title {
  text-align: center;
  font-size: 16px;
  margin: 0;
}
.btn-rules {
  position: absolute;
  right: 0.44rem;
  width: 0.5rem;
  height: 0.5rem;
  border-radius: 50%;
  border: 1px solid #ffffff;
  text-align: center;
  font-size: 0.35rem;
}
.benifit {
  text-align: center;
  font-size: 0.853rem;
  margin: 0;
}
.transaction h4 {
  position: relative;
}
.transaction .news {
  font-size: 14px;
  padding: 10px 0;
  color: #333333;
}
.transaction .btn {
  padding: 0.32rem 0.55rem;
  margin: 0;
}
.transaction .info-label {
  font-size: 0.4367rem;
  padding: 0.0667rem 0;
  color: #333333;
  font-weight: 500;
}
.transaction h4 div {
  top: 0.54rem;
  right: 0;
  position: absolute;
  color: #fddb3a;
}
.charts {
  display: flex;
  margin: 0.4rem 0;
}
.charts div {
  flex: auto;
}
.charts-wrapper {
  border-radius: 10px;
  background: url('../../static/imgs/tBg.png') no-repeat;
  background-size: cover;
  overflow: hidden;
}
.transaction .text-primary{
  color: #d3411d;
  text-align: center;
  border-bottom: 1px solid #f5f5f5;
  font-size: 0.4367rem;
}
.charts-main-info{
  padding: 0 0.0367rem;
}
.charts-main-info p{
  margin: 0;
}
h4 {
  font-weight: 400;
  font-size: 24px;
  color: #333333;
  letter-spacing: 0;
  padding: 20px 0;
  margin: 0;
}
h4 span{
  display: inline-block;
  width: 4px;
  height: 18px;
  background-color: #D3411D;
  margin-right: 13px;
}
h4 span:last-child(){
  margin-bottom: 0;
}
</style>
